/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dressingsocial.service;

/**
 *
 * @author hayate
 */
import com.dressingsocial.model.Role;
import com.dressingsocial.model.User;
import com.dressingsocial.repository.UserRepository;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    @Resource
    private UserRepository userRepository;

    //@Override
    @Transactional
    public User create(User user) {
        User createdUser = user;
        return userRepository.save(createdUser);
    }

    //@Override
    @Transactional
    public User findById(Long id) {
        return userRepository.findOne(id);
    }

    @Transactional
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
    
    @Transactional
    public Set<String> findRoleNameSetByEmail(String email) {
        User user = userRepository.findByEmail(email);
        List<Role> roles = user.getRoles();
        Set<String> set = new HashSet<String>();
        if (roles.size() != 0) {
            for (Role role : roles) {
                set.add(role.getName());
            }
        }
        return set;
    }
    
    @Transactional
    public User update(User user) {

        if (userRepository.findOne(user.getId()) != null) {
            User updatedUser = user;
            return userRepository.save(updatedUser);
        } else {
            user.setId(new Long(0));
            return user;
        }
    }
    
     @Transactional
     public List<User> findRecommendedUsers() {
        return userRepository.findAll();
     }
     
     
    /*
     //@Override
     @Transactional(rollbackFor=UserNotFound.class)
     public User delete(int id) throws UserNotFound {
     User deletedUser = userRepository.findOne(id);
		
     if (deletedUser == null)
     throw new UserNotFound();
		
     userRepository.delete(deletedUser);
     return deletedUser;
     }
    */
    
     
     @Transactional
     public List<User> findAll() {
        return userRepository.findAll();
     }
     
     /*
     //@Override
     @Transactional(rollbackFor=UserNotFound.class)
     public User update(User shop) throws UserNotFound {
     User updatedUser = userRepository.findOne(shop.getId());
		
     if (updatedUser == null)
     throw new UserNotFound();
		
     updatedUser.setName(shop.getName());
     updatedUser.setEmplNumber(shop.getEmplNumber());
     return updatedUser;
     }
     */
}
